package com.sinsoft.monitorDemo.util;

import java.util.ResourceBundle;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

//redis数据库连接池
public class RedisUtil {
	//redis地址
	public static String ADDR;
	//redis端口号
	public static Integer PORT;
	//redis登录名
	//public static String AUTH;
	//redis密码
	public static String PASSWORD;
	//redis最大连接数
	public static Integer MAX_TOTAL;
	//redis最大空闲连接数密码
	public static Integer MAX_IDLE;
	//redis最大等待时间
	public static Integer MAX_WAIT;
	
	public static Integer TIMEOUT;
	
	public static Integer redisID;
		
	//在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
	private static boolean TEST_ON_BORROW = true;
	
	public static JedisPool jedisPool = null;
	
	//获取配置信息
	static{
		ResourceBundle bundle = ResourceBundle.getBundle("redis");
		ADDR = bundle.getString("redis.addr");
		PORT = Integer.valueOf(bundle.getString("redis.port"));
		//AUTH = bundle.getString("redis.addr");
		PASSWORD = bundle.getString("redis.password");
		MAX_TOTAL = Integer.valueOf(bundle.getString("redis.MAX_TOTAL"));
		MAX_IDLE = Integer.valueOf(bundle.getString("redis.MAX_IDLE"));
		MAX_WAIT = Integer.valueOf(bundle.getString("redis.MAX_WAIT"));
		TIMEOUT = Integer.valueOf(bundle.getString("redis.TIMEOUT"));
		redisID = Integer.valueOf(bundle.getString("redis.no"));
	}
	//初始化连接池
	static{
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxIdle(MAX_IDLE);
			config.setMaxTotal(MAX_TOTAL);;;
			config.setMaxWaitMillis(MAX_WAIT);
			config.setTestOnBorrow(TEST_ON_BORROW);
			jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 生成Jedis实例
	 *redisID:指定数据库的ID 
	 * @return
	 */
	public synchronized static Jedis getJedis(){	
		try {
			if(jedisPool != null){
				Jedis jedis = jedisPool.getResource();
				jedis.select(redisID);
				return jedis;
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	/**
	 * 关闭jedis
	 * @param jedis
	 */
	public static void closeJedis(final Jedis jedis){
		if(jedis!=null){
			jedis.close();
		}
	}

}
